import Vue from 'vue';
import Router from 'vue-router';
import Store from '@/stores';
import Home from './modules/home';
import Login from './modules/login';

Vue.use(Router);

const vm = new Vue();

export const defaultRouterMap = [
  ...Home,
  ...Login,
  {
    path: '*',
    name: '404',
    component: () => import('@/views/error/404'),
  },
];

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    return savedPosition;
  } else {
    return { x: 0, y: 0 };
  }
};

const createRouter = () =>
  new Router({
    scrollBehavior,
    routes: defaultRouterMap,
  });

const router = createRouter();
const whiteList = ['/', '/login', '/setting', '/404'];

function checkToken() {
  vm.$dialog
    .confirm({
      title: '提示',
      message: '登录过期，请重新登录',
    })
    .then(() => {
      Store.commit('common/initCommonState');
      Store.commit('common/setKeepAlive', []);
      router.replace({
        path: '/login',
      });
    });
}

router.beforeEach((to, from, next) => {
  const { token } = Store.state.common;

  if (whiteList.includes(to.path)) {
    next();
  } else if (!token) {
    checkToken();
    next();
  } else {
    next();
  }
});

router.afterEach(() => {
  vm.$toast.clear();
});

export default router;
